package tree.二叉树展开链表;


import java.util.ArrayList;
import java.util.List;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public void flatten(TreeNode root) {
        List<TreeNode> list = new ArrayList<>();
        prevList(root, list);
        TreeNode current = root;
        for (int i = 1; i < list.size(); i++) {
            current.right = list.get(i);
            current.left = null;
            current = current.right;
        }
    }

    public void prevList(TreeNode node, List<TreeNode> list) {
        if (node == null) {
            return;
        }
        list.add(node);
        prevList(node.left, list);
        prevList(node.right, list);
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
//        [1,2,5,3,4,null,6]
        TreeNode treeNode = new TreeNode(1, new TreeNode(2, new TreeNode(3), new TreeNode(4)), new TreeNode(5, null, new TreeNode(6)));
        solution.flatten(treeNode);
        System.out.println(treeNode);
    }
}
